<template>
    <view v-if="!loading && detail" class="container">
        <view class="header">
            <!-- 音频 -->
            <!-- 视频 -->
            <view class="f-video relative" :class="{fullscreen: isFullscreen}">
                <video class="video w-full h-[450rpx] block" 
                    id="myVideo"
                    :controls="activityConfig?.show_loading == 1" 							
                    :src="img(activityDetail?.video_url)"
                    :enable-progress-gesture="false" 
                    :direction="90"
                    :poster="img(activityDetail?.back_image || activityConfig?.default_play_back)"
                    :custom-cache="false" 
                    :show-center-play-btn="false"
                    :object-fit="'cover'"
                    @error="handleVideoError" 
                    @timeupdate="handleVideoTimeupdate" 
                    @ended="handleVideoEnded"
                    @pause="handleVideoPause"
                    @waiting="handleVideoWaiting"
                ></video>
                <!-- 直播未开始 -->
                <div v-if="countDownTime" class="f-video__content">
                    <text class="text-[#fff] text-[36rpx] mb-[30rpx]">开播倒计时</text>
                    <u-count-down :time="countDownTime" format="DD 天 HH 时 mm 分 ss 秒" @end="handleCountDown"></u-count-down>
                </div>
                <!-- 直播中 / 回放中 -->
                <div v-else-if="activityDetail?.is_end != 1" class="f-video__content playing" @click="handleStopPlay">
                    <!-- 观看人数 -->
                    <view v-if="usernum>0" class="f-video__viewer">观看人数：{{usernum}}</view>
                    <view v-if="!videoPlaying" class="play-icon" @click.stop="handleStartPlay">
                        <image :src="activityConfig?.video_play_icon||'http://static.fastht.com/7d31304e239b9bb2/054ea5b1e471eafe.png'" mode="" style="width: 100rpx;height: 100rpx;">
                        </image>
                    </view>
                    <!-- 全屏 -->	
                    <view v-if="activityConfig?.is_full == 1" class="f-video__fullscreen" :class="{fullscreen: isFullscreen}" @click="isFullscreen = !isFullscreen"></view>
                </div>
                <!-- 直播已结束 / 回放未开始 -->
                <div v-else-if="activityDetail?.is_end == 1" class="f-video__content">
                    <text class="text-[#fff] text-[36rpx] mb-[30rpx]">直播已结束</text>
                    <text v-if="dati_time_no" class="text-[#fff] text-[28rpx]">观看时间不足{{parseInt(String(activityDetail.dati_time/60))}}分钟，无法答题</text>
                </div>
                <!-- 回放已结束 / 活动已结束 -->
                <!-- <div v-if="true" class="f-video__content">
                    <text class="text-[#fff] text-[36rpx] mb-[30rpx]">活动已结束</text>
                </div> -->
            </view>
        </view>
        <!-- 活动提示 -->
        <u-swiper v-if="activityDetail?.tips_src" height="125rpx" :list="[img(activityDetail?.tips_src)]"></u-swiper>
        <!-- 活动信息 -->
        <view class="p-[30rpx] flex items-center">
            <view class="flex-1">{{activityDetail?.title||'--'}}</view>
            <view class="ml-[20rpx] w-[200rpx] text-[12px] text-right">{{userInfo?.uid}}</view>
        </view>
        <!-- tab -->
         <u-sticky offset-top="450rpx" customNavHeight="0">
             <u-tabs :current="active" :scrollable="false" :list="tabs" @change="handleTabChange"></u-tabs>
         </u-sticky>
    
        <!-- 评论 -->
        <view v-if="activeValue==1" class="tab-item">
            <u-empty class="pt-[100rpx]" icon="empty" text="暂无评论"></u-empty>
        </view>
        <!-- 答题 -->
        <view v-if="activeValue==2" class="tab-item">
            <view v-if="answerList.length" class="subject">
                <view class="subject-item" v-for="(item,index) in answerList">
                    <view class="subject-item-title text-[28rpx]">
                        <up-tag class="mr-[10rpx]" :text="item.typename" size="mini" plain></up-tag>
                        <text>{{index + 1}}、</text>
                        <text>{{item.title}}</text>
                    </view>
                    <view class="mt-[20rpx]">
                        <view class="flex" v-for="(item2,index2) in item.xuanxiang">
                            <view class="mr-[10rpx]">{{item2.xuhao}}.</view>
                            <view>{{item2.val}}</view>
                        </view>
    
                    </view>
    
                </view>
            </view>
            <u-empty v-if="answerList.length==0" class="pt-[100rpx]" icon="empty" text="暂无答题信息"></u-empty>

            <view class="footer">
                <u-button v-if="canyu_status==1" type="primary" disabled>观看视频后前往答题</u-button>
                <u-button v-else-if="canyu_status==2" disabled>参与次数用完了</u-button>
                <u-button v-else-if="canyu_status==3" class="opacity" type="primary" @click="handleAnswer">前往答题</u-button>
                <u-button v-else-if="canyu_status==4" disabled>已获得奖励</u-button>
            </view>
        </view>
        <!-- 介绍 -->
        <view v-if="activeValue==3" class="tab-item">
            <view v-if="activityDetail?.detail" class="content" v-html="activityDetail?.detail"></view>
            <u-empty v-else class="pt-[100rpx]" icon="empty" text="暂无介绍"></u-empty>
        </view>

    </view>
    <up-empty v-if="!loading && !detail" class="pt-[200rpx]" :text="errorMessage" text-color="#333"></up-empty>

    <!-- 弹框 - 观看密码 -->
    <!-- 弹框 - 绑定手机号 -->
    <!-- 弹框 - 授权登录 -->
    <f-login-popup ref="loginPopupRef" />
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';
import { onHide, onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { reactive } from 'vue'; 
import FLoginPopup from '@/addon/htscrm/components/f-login-popup/index.vue'
import { useLogin } from '@/hooks/useLogin';
import { getConfigApi, getActivityDetailApi, getPlayTimeApi, updatePlaylogApi, getUvApi } from '../../api';
import { setToken, getToken, redirect, img } from '@/utils/common';
import useUserStore from '../../stores/user';
import { useShare } from '@/hooks/useShare';
import { asyncQueue } from '@/utils/queue';
  
const loading = ref(true)
const errorMessage = ref<string>()
// 分享
const { setShare } = useShare()
const userStore = useUserStore()

const options = ref<any>({})
const login = useLogin()
const loginPopupRef = ref<InstanceType<typeof FLoginPopup>>()

// 当前选项卡索引  
const active = ref(0) 
const activeValue = computed(() => tabs.value[active.value]?.value ?? 0) 

// 全屏播放
const isFullscreen = ref(false)

// 活动配置
const activityConfig = ref<IActivityConfig>()

const detail = ref<IActivityDetail>()


// 活动详情 
const activityDetail = computed(():IActivityDetail['activity_info']|undefined => {
    return detail.value?.activity_info
})

// 题目列表
const answerList = computed(():IActivityDetail['wentilist'] => {
    return detail.value?.wentilist ?? []
})

// 用户信息
const userInfo = computed(():IActivityDetail['user']|undefined => {
    return {...userStore.userInfo, ...(detail.value?.user||{})}
})

// 存储字段
const storageKey = computed(() => {
    return (key: string) => `${key}_${activityDetail.value?.id}`
})

// 视频播放控制
const videoRef = ref()
// 播放时长
const videoDuration = ref(0)
// 播放进度
const videoRealTime = ref(0)
// 是否开启可以视频快进
const fastForwardAllowed = ref(false)
const kuaijin_ok = ref(false)
// 播放状态
const videoPlaying = ref(false)
// 播放定时器
const playTimer = ref()
const usernumtimer = ref()
const usernum = ref(0)
// 已播放时间
const playtimeNumber = ref(0)
// 参与状态
const canyu_status = ref(1)
// 提示次数
const tip_times = ref(3)

const dati_time_no = ref(false)
const huodong_end = ref(false)

// 倒计时
const countDownTime = computed(() => {
    if(!activityDetail.value) return 0
    const { huodong_wait, starttime } = activityDetail.value
    if(huodong_wait == 1) {
        return (starttime - (Date.now()/1000) + 1) * 1000
    }
    return 0
})

// 创建响应式数据  
const tabs = computed(() => {
    return [  
        // { name: '评论', value: 1, disabled: !activityDetail.value?.chat_open },  
        { name: '答题', value: 2, disabled: !activityDetail.value?.is_open_answer },  
        { name: '介绍', value: 3, disabled: !activityDetail.value?.is_open_desc },  
    ].filter(item => !item.disabled)
});

// 本地播放时长
const playTime = ref(0)

function setPlayTime(value: number) {
    uni.setStorageSync(storageKey.value('playtime_new'), value)
    playTime.value = value
}

function getPlayTime() {
    playTime.value = Number(uni.getStorageSync(storageKey.value('playtime_new'))||0)
}

const isPlayOk = computed({
    get() {
        return Number(uni.getStorageSync(storageKey.value('playok')))
    },
    set (val:number) {
        uni.setStorageSync(storageKey.value('playok'), val)
    }
})


const canAnswer = computed(() => {
    const newtime = Date.now() / 1000;
    const { endtime } = activityDetail.value!
    return newtime >= endtime
})

/**
 * 获取详情
 * @param data 
 */
async function getDetail(data:any) {
    loading.value = true
    uni.showLoading()
    if(!data.store_id) {
        data.store_id = userInfo.value?.store_id
    }
    try {
        const res = await getActivityDetailApi(data)
        loading.value = false
        uni.hideLoading()
        detail.value = res.data
        canyu_status.value = res.data.canyu_status
        if (res.data.canyu_status == 1 && isPlayOk.value) {
            canyu_status.value = 3;
        } else {
            canyu_status.value = res.data.canyu_status; //参与状态
        }
        useUserStore().setUserInfo(res.data.user)
        
    } catch (error:any) {
        loading.value = false
        uni.hideLoading()
        if(error.code == 401) {
            loginPopupRef.value?.open()
        } else {
            errorMessage.value = error.msg
        }
    }
    
}
/**
 * 获取配置信息
 */
async function getConfig() {
    try {
        const res = await getConfigApi('activity')
        activityConfig.value = res.data
        
    } catch (error) {
        console.log(error);
        
    }
}

/**
 * 监听视频播放进度
 */
function handleVideoTimeupdate(e: any) {
    // 播放进度
    const { currentTime, duration } = e.detail;

    // 播放时长大于0，且当前播放时间大于0，且当前播放时间小于总时长
    if (videoDuration.value == 0 && parseFloat(duration) > 0 && e.type == "timeupdate") {
        videoDuration.value = parseFloat(duration);
    }
    
    // var playtime = uni.getStorageSync(key);


    const nowTime = currentTime.toFixed(0);
    if (nowTime % 2 == 0 && nowTime > 1) {
        setPlayTime(nowTime)
    } else if (nowTime > (duration - 1)) {
        setPlayTime(0)
    }

    // 视频如果不可以快进，则跳转到播放进度
    if (!fastForwardAllowed.value) {
        if ((currentTime - videoRealTime.value > 2) && !kuaijin_ok.value) {
            videoRef.value?.pause()
            videoRef.value?.seek(videoRealTime.value)
            setTimeout(() => {
                videoRef.value?.play()
            }, 100);
            return
        }
    }

    if (activityDetail.value?.ishuifang == 1) {
        videoRealTime.value = currentTime //实时播放进度
    } else {
        if (currentTime > 2) {
            videoRealTime.value = currentTime //实时播放进度
        }
    }

    kuaijin_ok.value = false;

    // 播放时长

}
/**
 * 监听视频播放错误
 */
function handleVideoError(e: any) {
    if(!activityDetail.value) return
    const { status } = activityDetail.value
    
    if (e.type == 'error' && (status && status == 1)) {
        uni.showModal({
            content: "网络状况不佳，请刷新重试",
            showCancel: true,
            confirmText: '刷新重试',
            success(res) {
                if (res.confirm) {
                    redirect({
                        url: '/addon/htscrm/pages/video/index',
                        param: options.value,
                        mode: 'redirectTo' 
                    })
                }
            }
        })

    }
}

/**
 * 监听视频播放结束
 */
function handleVideoEnded(e:any) {
    exitFullScreen();
    clearInterval(playTimer.value);
    // const key = storageKey.value('palaytime')
    // var playtime = uni.getStorageSync(key);
    
    if (e.type == 'ended') {
        // 获取总的播放时长
        var newPlaytimeNumber = updatePlayLog('videoEnded'); //更新播放时间

        // 播放完成
        isPlayOk.value = 1
        // 清除播放进度
        playTime.value = 0
        
        videoPlaying.value = false;   
        
        if (Number(newPlaytimeNumber) < Number(activityDetail.value?.dati_time)) {
            dati_time_no.value = true;
            huodong_end.value = true;
            return uni.showModal({
                title: '提示',
                content: "观看时长不足，无法参与答题！",
                showCancel: false
            })
        }
        
        if (canyu_status.value == 1 || canyu_status.value == 3) {
            canyu_status.value = 3;
            
	        redirect({ 
                url: '/addon/htscrm/pages/answer/index', 
                param: { 
                    activity_id: activityDetail.value?.id,
                    ids: detail.value?.ids
                }, 
                mode: 'redirectTo' 
            })

        }

    }
    

}

/**
 * 监听视频播放暂停
 */
function handleVideoPause() {
    updatePlayLog('videoPause')
}

/**
 * 监听视频点击
 */
function handleStopPlay() {
    // 是否可以暂停
    if(activityDetail.value?.video_stop !== 1) return
    videoPlaying.value = false
    videoRef.value?.pause();
}

/**
 * 监听视频播放开始
 */
function handleStartPlay() {
    const { ishuifang } = activityDetail.value || {}
    // 开始播放
    videoPlaying.value = true;
    console.log(1111, playTime.value);
    

    // 跳转到播放位置
    videoRef.value?.seek(playTime.value);
    setTimeout(() => {
        videoRef.value?.play();
    }, 100)
    
    // 更新播放时间
    updatePlayLog('startPlay');
    kuaijin_ok.value = true;
    // 开启计时器
    fnPlaytimer();
}

/**
 * 重新播放
 */
function handleReplay() {
    playTime.value = 0
    videoRef.value?.seek(0);
    setTimeout(() => {
        videoRef.value?.play();
    }, 100)
}

// const playtimeNumber = ref(0);
function fnPlaytimer() {
    clearInterval(playTimer.value);
    playTimer.value = setInterval(() => {

        playtimeNumber.value += 3;
        if (playtimeNumber.value >= 240) {
            updatePlayLog('timer')
            playtimeNumber.value = 0;
        }
    }, 3000)
}



/**
 * 监听视频缓冲中
 */
function handleVideoWaiting()  {

    if (playtimeNumber.value >300 && tip_times.value>0){
        uni.showToast({
            title: '您的本地网络不佳，请检查您的网络',
            icon: 'none',
            duration: 2000
        })
        tip_times.value --
    }

}

/**
 * 监听tab切换
 * @param value 
 */
function handleTabChange(value: any) {
    active.value = value.index
}

/**
 * 退出全屏
 */
function exitFullScreen() {
    isFullscreen.value = false;
}

/**
 * 更新播放记录
 * @param type 
 * @param update 
 */
function updatePlayLog(type:string, update:boolean = true) {
    const oldPlaytimeNumber: number = uni.getStorageSync(storageKey.value('playtimeNumber'))??0;
    
    var newPlaytimeNumber = oldPlaytimeNumber + playtimeNumber.value;

    if (update) {
        asyncQueue.enqueue(() => updateLog(type))
    }
    return newPlaytimeNumber;
}

function updateLog(type: string) {
    return new Promise((resolve, reject) => {
        // 记录最后一次上传的时间
        uni.setStorageSync(storageKey.value('update_play_log'), Date.now() / 1000);
        const params = {
            activity_id: activityDetail.value?.id,
            store_id:  userInfo.value?.store_id,
            type: type,
            playtime_number: playtimeNumber.value,
            current_time: videoRealTime.value
        }

        if(!params.activity_id) return
        // update 播放时间
        updatePlaylogApi(params).then((res:any) => {
            playtimeNumber.value = 0;
            if (activityDetail.value?.video_unfinished_dati && res.data.newplaytime_number >= activityDetail.value?.dati_time && canyu_status.value == 1 ){
                canyu_status.value = 3;
            }
            uni.setStorageSync(storageKey.value('playtimeNumber'), res.data.newplaytime_number);

            resolve(res)
        }).catch(err => {
            reject(err)
        })

    })
}

/**
 * 去答题
 */
async function handleAnswer() {
    // 直播结束才能去答题
    if (!isPlayOk.value) {
        uni.showModal({
            title: '提示',
            content: "直播结束后才可以答题喔！",
            showCancel: false,
        })
        return 
    }

    // 观看时长足够才可以去答题

    const {dati_time} = activityDetail.value!
    var hdtime = parseInt(String(dati_time / 60));

    const res:any = await getPlayTimeApi({
        activity_id: activityDetail.value?.id,
    })

    if (res.code == 1) {
        if (res.data.playtime_pumber < dati_time) {

            return uni.showModal({
                title: '提示',
                content: "观看时间不足" + hdtime + "分钟，不可答题=" + res.data.playtime_pumber,
                showCancel: false,
            })
        } else {

            redirect({ 
                url: '/addon/htscrm/pages/answer/index', 
                param: { 
                    activity_id: activityDetail.value?.id,
                    ids: detail.value?.ids
                }, 
                mode: 'navigateTo' 
            })

        }
    } else {
        uni.showModal({
            title: "提示",
            content: res.msg,
            showCancel: false
        })
    }
}

/**
 * 倒计时
 */
function handleCountDown() { //定时器执行完，
    if (activityDetail.value?.huodong_wait == 1) {
        uni.showModal({
            title: '提示',
            content: '直播开始了',
            showCancel: false,
            confirmText: "立即播放", //这块是确定按钮的文字
            success(res) {
                location.href = location.href;
            }
        })
    }
}

/**
 * 初始化数据
 * @param data 详情数据
 */
async function init(data: any) {
    options.value = data
    await getConfig()
    await getDetail(data)

    updatePlayLog('onLoad')
    openUserTimer()

    // 设置标题
    uni.setNavigationBarTitle({
        title: activityConfig.value?.activity_info_title || activityDetail.value?.title || '活动详情'
    });

    const share = {
        title: activityDetail.value?.share_title || '',
        desc: activityDetail.value?.share_desc || '',
        url: activityDetail.value?.share_image || '',
        link: window.location.href + '&tid=' + userInfo.value?.uid
    }
    
    setShare({
        wechat: {
            ...share
        },
        weapp: {
            ...share
        }
    })
}

function openUserTimer() {
    clearInterval(usernumtimer.value)
    
    usernumtimer.value = setInterval(async function() {
        const res:any = await getUvApi({
            activity_id: activityDetail.value?.id
        })
        usernum.value = res.data.uv;
    }, 60000)

}


onLoad((e: any) => {
    // setToken('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtZW1iZXJfaWQiOjI0LCJ1c2VybmFtZSI6IiIsInVpZCI6MjU2OTM5LCJpc3MiOiJ0MS5mYXN0aHQuY29tIiwiYXVkIjoidDEuZmFzdGh0LmNvbSIsImlhdCI6MTc0MTE2MjE2MiwibmJmIjoxNzQxMTYyMTYyLCJleHAiOjE3NDEyNDg1NjIsImp0aSI6IjI0X2FwaSJ9.eknmNhAdSOI1w4Q8O62KYIrnsaJltNMUpttVVISIXMY')
    if (e.scene) {
        var scene = e.scene;
        var sceneArr = scene.split('-');
        e.activity_id = sceneArr[0];
        e.store_id = sceneArr[1];
    }
    const { code, ...data} = e

    if(code && code !== uni.getStorageSync('wx_code')) {
        uni.setStorageSync('wx_code', code)
        login.authLogin({ code, successCallback: () => init(data) }, data)
        return
    }
    
    // token 是否存在
    if(!getToken()) {
        nextTick(() => {
            loginPopupRef.value?.open()
        })
    } else {
        init(data)
    }
})

onShow(() => {
    nextTick(() => {
        videoRef.value = uni.createVideoContext('myVideo')
        getPlayTime()
    })
})
onHide(function () {
    videoPlaying.value = false;
    videoRef.value.pause();
    clearInterval(playTimer.value);
    // videoRef.value.stop();
    updatePlayLog('onHide');
    playtimeNumber.value = 0;

})
onUnload(function () {
    clearInterval(usernumtimer.value)
    clearInterval(playTimer.value);
    videoPlaying.value = false;
    videoRef.value.stop();

    updatePlayLog('onUnload');
    playtimeNumber.value = 0;
})
</script>
<style lang="scss" scoped>
.f-video {
    // transition: all 0.3s;
    &.fullscreen {
        position: fixed;
        top: 50%;
        left: 50%;
        width: 100vh;
        height: 100vw;
        z-index: 99999;
        transform: translate(-50%, -50%) rotate(90deg);
        transform-origin: center;
        background-color: #000;

        .video {
            width: 100%;
            height: 100%;
        }
        // .play-icon {
        //     height: 100vw;
        // }
    }
    .f-video__content {
        background: rgba(0, 0, 0, 0.5);
        z-index: 100;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    
        :deep(.u-count-down__text) {
            color: #fff;
        }
    
        &.playing {
            background-color: rgba($color: #000000, $alpha: 0.2);
        }
    }
    
    .f-video__viewer {
        position: absolute;
        top: 14rpx;
        left: 14rpx;
        background: rgba(0, 0, 0, 0.5);
        color: #fff;
        z-index: 999;
        font-size: 24rpx;
        padding: 8rpx 14rpx;
        border-radius: 10rpx;
        height: 38rpx;
        line-height: 32rpx;
    
    }
    
    .f-video__fullscreen {
        position: absolute;
        bottom: 0;
        right: 0;
        // background: #673ab766;
        width: 156rpx;
        height: 66rpx;
        opacity: 0.8;
    
        &::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('~@/addon/htscrm/assets/quanping.jpg') center/100% no-repeat;
            opacity: 1;
        }
        &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('~@/addon/htscrm/assets/tuichuquanping.jpg') center/100% no-repeat;
            opacity: 0;
        }
    
        &.fullscreen {
            &::after {
                opacity: 0;
            }
    
            &::before {
                opacity: 1;
            }
        }
    }
}

.container {
    background-color: #f6f7f8;
    min-height: 100vh;

    .header {
        position: sticky;
        top: 0;
        z-index: 971;
    }

    .u-tabs {
        background: #fff;
    }

    .subject {
        padding: 30rpx;
        padding-bottom: 170rpx;
    
        .subject-item {
            padding: 30rpx;
            background-color: #FFF;
            border-radius: 12rpx;
            
            &:not(:last-child) {
                margin-bottom: 30rpx;
            }

            .subject-item-title {
                line-height: 48rpx;
            }
        }
    }

    .footer {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 30rpx;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .opacity {
        background-color: rgba(0, 122, 255, 0.5);
        border-color: rgba(0, 122, 255, 0.5);
    }


    .content {
        padding: 30rpx;
    }
}

</style>
